package com.shenyue.nbtownlet.activity;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.base.BaseActivity;
import com.shenyue.nbtownlet.databinding.ActivityFileBinding;
import com.shenyue.nbtownlet.model.DefaultModel;
import com.shenyue.nbtownlet.util.ActivityUtil;
import com.shenyue.nbtownlet.util.MD5Util;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.request.RequestCall;

import java.io.File;

import okhttp3.Call;

public class TXTActivity extends BaseActivity {
    private ActivityFileBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_file);
        Bundle bundle = getIntent().getExtras();
        String url = bundle.getString(DefaultModel.URL);
        String fileName = url.substring(url.lastIndexOf("/") + 1);
        setActionBar(true, fileName);

        WebSettings webSettings = binding.webView.getSettings();
        webSettings.setTextZoom(100);
        //支持屏幕缩放
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        //不显示webview缩放按钮
        webSettings.setDisplayZoomControls(false);
        webSettings.setDefaultFontSize(14);

        binding.webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                binding.progressLayout.showContent();
            }
        });

        binding.progressLayout.showProgress();

        String mDDirPath = ActivityUtil.getMSDCardPath();
        mDDirPath = mDDirPath + "/" + DefaultModel.DOWNLOAD_DIR_NAME;
        File file = new File(mDDirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        fileName = MD5Util.md5(url) + ".txt";
        File pdf = new File(mDDirPath + "/" + fileName);
        if (pdf.exists()) {
            openFile(pdf);
            return;
        }
        RequestCall call = OkHttpUtils.get().url(url).build();
        call.execute(new FileCallBack(mDDirPath, fileName) {
            @Override
            public void inProgress(float progress, long total, int id) {
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                binding.progressLayout.showContent();
            }

            @Override
            public void onResponse(File file, int id) {
                openFile(file);
            }
        });
    }

    private void openFile(File file) {
        binding.webView.loadUrl("file://" + file.getAbsolutePath());
    }
}
